package com.fy.fyspace.ex.handler;

import cn.dev33.satoken.exception.NotLoginException;
import com.fy.fyspace.common.result.Result;
import com.fy.fyspace.constant.ResultMessageConstant;
import com.fy.fyspace.ex.BaseException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 处理Sa-Token的NotLoginException异常
     */
    @ExceptionHandler(NotLoginException.class)
    public Result<String> handleNotLoginException(NotLoginException e) {
        String message;
        if (NotLoginException.NOT_TOKEN.equals(e.getType())) {
            message = "请先登录!";
        } else if (NotLoginException.INVALID_TOKEN.equals(e.getType())) {
            message = "登录状态已失效，请重新登录!";
        } else if (NotLoginException.TOKEN_TIMEOUT.equals(e.getType())) {
            message = "登录已过期，请重新登录!";
        } else if (NotLoginException.BE_REPLACED.equals(e.getType())) {
            message = "您的账号已在其他设备登录，如非本人操作，请及时修改密码!";
        } else if (NotLoginException.KICK_OUT.equals(e.getType())) {
            message = "您已被强制下线，如有疑问请联系管理员!";
        } else {
            message = "请先登录!";
        }
        log.warn("用户未登录: type={}, message={}", e.getType(), message);
        return Result.error(message);
    }

    /**
     * 处理业务异常
     */
    @ExceptionHandler(BaseException.class)
    public Result<String> handleBaseException(BaseException e) {
        log.warn("业务异常: {}", e.getMessage());
        return Result.error(e.getMessage());
    }

    /**
     * 处理其他未知异常
     */
    @ExceptionHandler(Exception.class)
    public Result<String> handleException(Exception e) {
        log.error("系统异常", e);
        return Result.error(ResultMessageConstant.SYSTEM_ERROR);
    }

    /**
     * 处理参数校验异常
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result<Void> handleValidationException(MethodArgumentNotValidException e) {
        log.warn("参数校验失败: {}", e.getMessage());
        return Result.error(buildErrorMessage(e.getBindingResult()));
    }

    /**
     * 处理参数绑定异常
     */
    @ExceptionHandler(BindException.class)
    public Result<Void> handleBindException(BindException e) {
        log.warn("参数绑定失败: {}", e.getMessage());
        return Result.error(buildErrorMessage(e.getBindingResult()));
    }


    /**
     * 处理业务异常
     */
    @ExceptionHandler(IllegalArgumentException.class)
    public Result<Void> handleIllegalArgumentException(IllegalArgumentException e) {
        log.warn("业务异常: {}", e.getMessage());
        return Result.error(e.getMessage());
    }

    /**
     * 构建错误信息
     */
    private String buildErrorMessage(BindingResult result) {
        List<FieldError> fieldErrors = result.getFieldErrors();
        return fieldErrors.stream()
                .map(error -> String.format("%s: %s", error.getField(), error.getDefaultMessage()))
                .collect(Collectors.joining("; "));
    }
}
